<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入资讯标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="公司" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="请选择公司" clearable>
          <el-option v-for="item in companyList" :key="item.companyId" :label="item.companyNameCn" :value="item.companyId" />
        </el-select>
      </el-form-item>
      <el-form-item label="资讯类型" prop="articleType">
        <el-select v-model="queryParams.articleType" placeholder="请选择资讯类型" clearable>
          <el-option v-for="dict in dict.type.tzai_article_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择处理状态" clearable>
          <el-option label="待处理" value="0" />
          <el-option label="AI处理中" value="1" />
          <el-option label="TTS生成中" value="2" />
          <el-option label="已完成" value="3" />
          <el-option label="失败" value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理模式" prop="processMode">
        <el-select v-model="queryParams.processMode" placeholder="请选择处理模式" clearable>
          <el-option label="摘要处理" value="summary" />
          <el-option label="全文处理" value="full" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['tzai:article:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['tzai:article:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['tzai:article:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-s-operation" size="mini" :disabled="single" @click="handleProcess" v-hasPermi="['tzai:article:process']">处理资讯</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资讯ID" align="center" prop="articleId" width="80" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="公司" align="center" prop="companyNameCn" width="150" :show-overflow-tooltip="true" />
      <el-table-column label="资讯类型" align="center" prop="articleType" width="140">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tzai_article_type" :value="scope.row.articleType"/>
        </template>
      </el-table-column>
      <el-table-column label="来源" align="center" prop="source" width="120" />
      <el-table-column label="处理状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'" type="info">待处理</el-tag>
          <el-tag v-else-if="scope.row.status === '1'" type="warning">AI处理中</el-tag>
          <el-tag v-else-if="scope.row.status === '2'" type="primary">TTS生成中</el-tag>
          <el-tag v-else-if="scope.row.status === '3'" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.status === '4'" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="处理模式" align="center" prop="processMode" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.processMode === 'full'" type="success">全文</el-tag>
          <el-tag v-else type="info">摘要</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-s-operation" @click="handleProcess(scope.row)" v-hasPermi="['tzai:article:process']" v-if="scope.row.status === '0' || scope.row.status === '4'">处理</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['tzai:article:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['tzai:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改资讯对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="资讯标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入资讯标题" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联公司" prop="companyId">
              <el-select v-model="form.companyId" placeholder="请选择公司">
                <el-option v-for="item in companyList" :key="item.companyId" :label="item.companyNameCn" :value="item.companyId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资讯类型" prop="articleType">
              <el-select v-model="form.articleType" placeholder="请选择资讯类型">
                <el-option v-for="dict in dict.type.tzai_article_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源" prop="source">
              <el-input v-model="form.source" placeholder="请输入来源" maxlength="100" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="原文链接" prop="sourceUrl">
              <el-input v-model="form.sourceUrl" placeholder="请输入原文链接" maxlength="500" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理模式" prop="processMode">
              <el-select v-model="form.processMode" placeholder="请选择处理模式">
                <el-option label="摘要处理（更快，简短）" value="summary" />
                <el-option label="全文处理（不缩短，分句+翻译+TTS）" value="full" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="资讯内容" prop="content">
              <el-input v-model="form.content" type="textarea" :rows="8" placeholder="请输入资讯内容，AI将基于此内容生成摘要、翻译和音频" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="语言" prop="language">
              <el-select v-model="form.language" placeholder="请选择语言">
                <el-option label="中文" value="cn" />
                <el-option label="英文" value="en" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker clearable v-model="form.publishTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择发布时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle, processArticle } from "@/api/tzai/article";
import { listCompany } from "@/api/tzai/company";

export default {
  name: "Article",
  dicts: ['tzai_article_type'],
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      articleList: [],
      companyList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        companyId: null,
        articleType: null,
        status: null,
        processMode: null
      },
      form: {},
      rules: {
        title: [
          { required: true, message: "资讯标题不能为空", trigger: "blur" }
        ],
        companyId: [
          { required: true, message: "关联公司不能为空", trigger: "change" }
        ],
        articleType: [
          { required: true, message: "资讯类型不能为空", trigger: "change" }
        ],
        source: [
          { required: true, message: "来源不能为空", trigger: "blur" }
        ],
        processMode: [
          { required: true, message: "请选择处理模式", trigger: "change" }
        ],
        sourceUrl: [
          { required: true, message: "原文链接不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "资讯内容不能为空", trigger: "blur" },
          { min: 10, message: "内容长度至少10个字符", trigger: "blur" }
        ],
        language: [
          { required: true, message: "请选择语言", trigger: "change" }
        ],
        publishTime: [
          { required: true, message: "发布时间不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCompanyList();
  },
  methods: {
    /** 查询资讯列表 */
    getList() {
      this.loading = true;
      listArticle(this.queryParams).then(response => {
        this.articleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询公司列表 */
    getCompanyList() {
      listCompany({ status: 1 }).then(response => {
        this.companyList = response.rows || [];
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        articleId: null,
        title: null,
        companyId: null,
        articleType: 'earnings_call',
        source: null,
        sourceUrl: null,
        content: null,
        processMode: 'summary',
        language: 'cn',
        publishTime: null,
        status: '0'
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.articleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资讯";
    },
    handleUpdate(row) {
      this.reset();
      const articleId = row.articleId || this.ids
      getArticle(articleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资讯";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.articleId != null) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const articleIds = row.articleId || this.ids;
      this.$modal.confirm('是否确认删除资讯编号为"' + articleIds + '"的数据项？').then(function() {
        return delArticle(articleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 处理资讯 */
    handleProcess(row) {
      const articleId = row.articleId || this.ids[0];
      this.$modal.confirm('是否确认处理该资讯？将按“处理模式”生成分句、翻译与音频。').then(function() {
        return processArticle(articleId);
      }).then(() => {
        this.$modal.msgSuccess("处理任务已提交，请稍后刷新查看结果");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>

